﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

namespace FlashPay.Admin.Controllers
{
    using FlashPay.Admin.ViewModels.Menu;
    using FlashPay.Admin.ViewModels.User;
    using FlashPay.Entity;
    using FlashPay.Entity.Enum;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Request.SysAnnouncement;
    using FlashPay.Entity.Request.User;
    using FlashPay.Entity.Response.SysAnnouncement;
    using FlashPay.Entity.Response.User;
    using FlashPay.Service.Interface;
    using Microsoft.AspNetCore.Http;

    /// <summary>
    /// 首页控制器
    /// </summary>
    public class HomeController : BaseController
    {
        #region 注入
        /// <summary>
        /// 授权业务接口
        /// </summary>
        private readonly AuthorizeService _authorizeService;

        /// <summary>
        /// 菜单业务接口
        /// </summary>
        private readonly MenuService _menuService;

        /// <summary>
        /// 用户业务接口
        /// </summary>
        private readonly UserInfoService _userInfoService;

        /// <summary>
        /// 公告业务接口
        /// </summary>
        private readonly SysAnnouncementService _sysAnnouncementService;
        
        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="menuService"></param>
        /// <param name="authorizeService"></param>
        /// <param name="userInfoService"></param>
        public HomeController(IAuthenticate<TicketResponse> _manage, IHttpContextAccessor _accessor, AuthorizeService authorizeService, MenuService menuService, UserInfoService userInfoService, SysAnnouncementService sysAnnouncementService) : base(_manage, _accessor)
        {
            _authorizeService = authorizeService;
            _menuService = menuService;
            _userInfoService = userInfoService;
            _sysAnnouncementService = sysAnnouncementService;
        }
        #endregion

        #region 菜单
        /// <summary>
        /// 菜单
        /// </summary>
        /// <returns></returns>
        public JsonResult GetMenu()
        {
            //输出
            var response = new JResult<List<MenuViewModel>>()
            {
                Success = false,
                StatusCode = "fram-logo-c"
            };

            try
            {
                if (_manage.data.PlatformType == PlatformType.B2B.GetHashCode()){
                    response.StatusCode = "fram-logo-b";
                }
                var authorizes = _authorizeService.GetMenuAuthorizes(new Entity.Parameter.AuthorizeQuery()
                {
                    UserSysNo = _manage.data.UserID,
                    RoleStatus = RoleStatus.显示.GetHashCode(),
                    AuthorizeType = AuthorizeType.菜单.GetHashCode()
                });

                var menuList = _menuService.GetListByIds(authorizes.Select(p => p.AuthPid).Distinct().ToList()).Where(p => p.Hide == MenuStatus.显示.GetHashCode()).ToList();
                if (menuList != null && menuList.Any())
                {
                    var menus = new List<MenuViewModel>();

                    var parentMenu = menuList.Where(p => p.MParent == 0).OrderBy(p=>p.SortNo).ToList();
                    foreach (var itemParent in parentMenu)
                    {
                        #region 子
                        var childMenus = menuList.Where(p => p.MParent == itemParent.Mid).OrderBy(p=>p.SortNo).ToList();

                        var childMenuList = new List<ChildMenu>();

                        foreach (var itemChild in childMenus)
                        {
                            var url = itemChild.MUrl;
                            if (_manage.data.PlatformType == PlatformType.B2B.GetHashCode())
                            {
                                if (itemChild.MName.Contains("库存卡管理") || itemChild.MName.Contains("银行卡管理"))
                                {
                                    url = string.Format(itemChild.MUrl, "b2b");
                                }
                                else
                                {
                                    url = string.Format(itemChild.MUrl, "");
                                }
                            }
                            else {
                                url = string.Format(itemChild.MUrl, "");
                            }
                            childMenuList.Add(new ChildMenu()
                            {
                                Id = itemChild.Mid,
                                Name = itemChild.MName,
                                Url = url
                            });
                        }
                        #endregion

                        menus.Add(new MenuViewModel()
                        {
                            Id = itemParent.Mid,
                            Name = itemParent.MName,
                            Url = itemParent.MUrl,
                            ChildMenus = childMenuList
                        });

                    }
                    response.Data = menus;
                }
                response.Success = true;
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }
            return Json(response);
        }
        #endregion

        #region 公告管理
        /// <summary>
        /// 获取公告
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult GetSysAnnouncement(int? id)
        {
            if (id.HasValue)
            {
                var model = _sysAnnouncementService.Get(id.Value);
                return Json(model);
            }
            else {
                return Json(new JResult<SysAnnouncementResponse>() { Success = true,Data = null });
            }
        }

        /// <summary>
        /// 公告保存或修改
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AuthorizeFilter(AuthCode.SysConfig0007)]
        public JsonResult SaveOrEdit(SaveOrEditSysAnnouncementRequest request)
        {
            request.CreateId = _manage.data.UserID;

            var response = _sysAnnouncementService.SaveOrEdit(request);
            return Json(response);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.SysConfig0008)]
        public JsonResult Delete(int id)
        {
            var response = new JResult()
            {
                Success = false
            };
            response.Success = _sysAnnouncementService.Delete(id);
            if (response.Success)
            {
                response.SuccessMessage = "操作成功！";
            }
            else {
                response.ErrorMessage = "操作失败！";
            }
            return Json(response);
        }

        /// <summary>
        /// 获取公告列表
        /// </summary>
        /// <returns></returns>
        public JsonResult GetList()
        {
            var query = new SysAnnouncementQuery() {
                UserPermission = _manage.data.UserPermission
            };
            var response = _sysAnnouncementService.GetList(query);
            return Json(response);
        }
        #endregion

        #region 修改密码
        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        public JsonResult getUser()
        {
            //输出
            var response = new JResult<UserInfoResponse>()
            {
                Success = false
            };

            try
            {
                var token = HttpContext.Request.Headers["token"];

                var ticketResponse = new TicketResponse();

                if (!string.IsNullOrEmpty(token))
                {
                    ticketResponse = _manage.Get(token);
                }

                var userInfo = _userInfoService.Get(ticketResponse.UserID);
                if (userInfo.Data != null) {
                    response.Success = true;
                    response.Data = new UserInfoResponse() {
                        UserName = userInfo.Data.ULoginName
                    };
                }
            }
            catch (Exception ex) {
                response.ErrorMessage = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public JsonResult EditPassWord(UpdatePassWordViewModel request)
        {
            //输出
            var response = new JResult()
            {
                Success = false
            };

            if (!ModelState.IsValid)
            {
                var message = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).FirstOrDefault();
                response.Success = false;
                response.ErrorMessage = message;
                return Json(response);
            }

            var updatePassWordPara = new UpdatePassWordRequest() {
                Id = _manage.data.UserID,
                OldPassword = request.OldPassword,
                NewPassword = request.NewPassword,
                ConfirmNewPassword = request.ConfirmNewPassword
            };
            response = _userInfoService.UpdatePassWord(updatePassWordPara);

            
            return Json(response);
        }


        /// <summary>
        /// 重置密码(不需要旧密码)
        /// </summary>
        /// <returns></returns>
        [AuthorizeFilter(AuthCode.User0012)]
        public JsonResult ResetPassWord(ResetPassWordViewModel request)
        {
            //输出
            var response = new JResult()
            {
                Success = false
            };

            if (!ModelState.IsValid)
            {
                var message = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).FirstOrDefault();
                response.Success = false;
                response.ErrorMessage = message;
                return Json(response);
            }

            var updatePassWordPara = new UpdatePassWordRequest()
            {
                Id = request.UID,
                NewPassword = request.NewPassword,
                ConfirmNewPassword = request.ConfirmNewPassword
            };
            response = _userInfoService.UpdatePassWord(updatePassWordPara);
            return Json(response);
        }

        #endregion
    }
}
